﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;

namespace Charities
{
    public partial class RolesMgmt : Form
    {
        int userId = -1;
        public RolesMgmt(int id,Form m)
        {
            fo = m;
            this.MdiParent = m;
            userId = id;
            InitializeComponent();
        }
        public RolesMgmt()
        {
            InitializeComponent();
        }
        ModelContainer ctx = new ModelContainer();
        Form fo = null;
        public bool is_loaded = false;
        private void RolesMgmt_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userId);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Id)
                {
                    case 44:
                        btn_Add.Visible = true;
                        break;
                    case 45:
                        btn_update.Visible = true;
                        break;
                    case 46:
                        btn_delete.Visible = true;
                        break;
                    default:
                        break;
                }
            }
            roleBindingSource.DataSource = ctx.Roles.ToList();
            lstbox_roles.DataSource = roleBindingSource;
            bindingSourceAllPermissions.DataSource = ctx.Permissions.ToList();
            ((ListBox)chkLibox_allPermissions).DataSource = bindingSourceAllPermissions;
            ((ListBox)chkLibox_allPermissions).DisplayMember = "Name";
            ((ListBox)chkLibox_allPermissions).ValueMember = "Id";
            if (lstbox_roles.SelectedValue != null)
            {
                int id=(int)lstbox_roles.SelectedValue;
                if (id > 0)
                {
                    bindingSourcePermissions.DataSource = ctx.Roles.Single(r => r.Id == id).Permissions.OrderBy(p=>p.Id).ToList();
                    ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                    ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                    ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                }
            }
        }
        private void DisSelectAll()
        {
            for (int i = 0; i < chkLbox_RolePermissions.Items.Count; i++)
            {
                chkLbox_RolePermissions.SetItemChecked(i, false);
            }
        }
        private void lstbox_roles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstbox_roles.SelectedValue != null)
            {
                tmpRoleId = (int)lstbox_roles.SelectedValue;
                bindingSourcePermissions.DataSource = ctx.Roles.Single(r => r.Id == tmpRoleId).Permissions.OrderBy(p => p.Id).ToList();
                ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                btnAddAll.Enabled = true;
                btnAddOne.Enabled = true;
                btnRemoveAll.Enabled = true;
                btnRemoveOne.Enabled = true;
            }
        
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            txb_rname.Visible = true;
            txb_rname.Text = String.Empty;
            btn_save.Visible = true;
            btn_update.Visible = false;
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            txb_rname.Text.Trim();
            if (txb_rname.Text != "")
            {
                try
                {
                    Role tmp = ctx.Roles.Single(c => c.Name == txb_rname.Text);
                    MessageBox.Show("اسم الدور موجود مسبقاً");
                }
                catch (Exception)
                {
                    Role r = new Role();
                    r.Name = txb_rname.Text;
                    r.InsertDate = DateTime.Now;
                    r.InsertUId = 1;
                    ctx.Roles.Add(r);
                    ctx.SaveChanges();
                }
                lstbox_roles.DataSource = null;
                roleBindingSource.DataSource = ctx.Roles.ToList();
                lstbox_roles.DataSource = roleBindingSource;
                lstbox_roles.DisplayMember = "Name";
                lstbox_roles.ValueMember = "Id";
            }
            else
            {
                MessageBox.Show("يرجى اختيار اسم صالح للادخال");
            }
        }

        private void btn_update_Click(object sender, EventArgs e)
        {
            try
            {
                Role tmpr = ctx.Roles.Single(x => x.Name == txb_rname.Text);
                MessageBox.Show("اسم الدور موجود مسبقاً");
            }
            catch (Exception)
            {
                Role r = ctx.Roles.Single(c => c.Id == tmpRoleId);
                r.Name = txb_rname.Text;
                ctx.SaveChanges();
            }

            roleBindingSource.DataSource = ctx.Roles.ToList();
            lstbox_roles.DataSource = roleBindingSource;
            lstbox_roles.DisplayMember = "Name";
            lstbox_roles.ValueMember = "Id";
            txb_rname.Visible = false;
            btn_update.Enabled = false;
 
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {

            try
            {
                DialogResult res = MessageBox.Show("هل أنت متأكد من حذف الدور وكافة صلاحياته؟","تاكيد الحذف",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
                if (res == DialogResult.Yes)
                {
                    if (lstbox_roles.SelectedValue != null)
                    {
                        int rid = (int)lstbox_roles.SelectedValue;
                        if (rid > 0)
                        {
                            Role r0 = ctx.Roles.Single(x => x.Id == rid);
                            if (ctx.Users.Where(c => c.RoleId == r0.Id).Count() == 0)
                            {
                                ctx.Roles.Remove(r0);
                                ctx.SaveChanges();
                                roleBindingSource.DataSource = ctx.Roles.ToList();
                                lstbox_roles.DataSource = roleBindingSource;
                                try
                                {
                                    if (lstbox_roles.SelectedValue != null)
                                    {
                                        if ((int)lstbox_roles.SelectedValue > 0)
                                        {
                                            tmpRoleId = (int)lstbox_roles.SelectedValue;
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    MessageBox.Show("لايمكن الحذف");
                                    tmpRoleId = ctx.Roles.First(c => c.Id != 0).Id;
                                }
                            }
                            else
                            {
                                MessageBox.Show("لايمكن حذف دور منتسب اليه مستخدمين");
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

        }
        int tmpRoleId;
        private void lstbox_roles_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            txb_rname.Visible = true;
            btn_save.Visible = false;
            btn_update.Visible = true;
            int id = (int)lstbox_roles.SelectedValue;
            Role r = ctx.Roles.Single(c => c.Id == id);
            txb_rname.Text = r.Name;
            tmpRoleId = r.Id;
        }

        private void lstbox_roles_MouseClick(object sender, MouseEventArgs e)
        {
            txb_rname.Visible = false;
            btn_save.Visible = false;
            btn_update.Visible = false;
            int id = (int)lstbox_roles.SelectedValue;
            Role r = ctx.Roles.Single(c => c.Id == id);
            tmpRoleId = r.Id;
        }


        private void RolesMgmt_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void RolesMgmt_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }

        private void txb_rname_TextChanged(object sender, EventArgs e)
        {
            btn_update.Enabled = true;
        }

        private void btnAddAll_Click(object sender, EventArgs e)
        {
            int roleId;
            if (lstbox_roles.SelectedValue != null)
            {
                roleId=(int)lstbox_roles.SelectedValue ;

                if (roleId > 0)
                {
                    Role role = ctx.Roles.Single(r => r.Id == roleId);
                    foreach (var perm in ctx.Permissions.ToList())
                    {
                        if (role.Permissions.Count(pr => pr.Id == perm.Id) == 0)
                        {
                            role.Permissions.Add(perm);
                        }
                    }
                    ctx.SaveChanges();
                    bindingSourcePermissions.DataSource = ctx.Roles.Single(r => r.Id == role.Id).Permissions.OrderBy(p => p.Id).ToList();
                    ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                    ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                    ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                }
            }
        }

        private void btnAddOne_Click(object sender, EventArgs e)
        {
            int roleId;
            if (lstbox_roles.SelectedValue != null)
            {
                roleId = (int)lstbox_roles.SelectedValue;

                if (roleId > 0)
                {
                    Role role = ctx.Roles.Single(r => r.Id == roleId);
                    foreach (Permission perm in chkLibox_allPermissions.CheckedItems)
                    {
                        
                        if (role.Permissions.Count(pr => pr.Id == perm.Id) == 0)
                        {
                            role.Permissions.Add(perm);
                        }
                    }
                    ctx.SaveChanges();
                    bindingSourcePermissions.DataSource = null;
                    bindingSourcePermissions.DataSource = ctx.Roles.Single(ro => ro.Id == roleId).Permissions.OrderBy(p => p.Id).ToList();
                    ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                    ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                    ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                }
            }
        }

        private void btnRemoveAll_Click(object sender, EventArgs e)
        {
            int roleId;
            if (lstbox_roles.SelectedValue != null)
            {
                roleId = (int)lstbox_roles.SelectedValue;

                if (roleId > 0)
                {
                    Role role = ctx.Roles.Single(r => r.Id == roleId);
                    role.Permissions.Clear();
                    ctx.SaveChanges();
                    bindingSourcePermissions.DataSource = null;
                    bindingSourcePermissions.DataSource = ctx.Roles.Single(ro => ro.Id == roleId).Permissions.OrderBy(p => p.Id).ToList();
                    ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                    ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                    ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                }
            }
        }

        private void btnRemoveOne_Click(object sender, EventArgs e)
        {
            int roleId;
            if (lstbox_roles.SelectedValue != null)
            {
                roleId = (int)lstbox_roles.SelectedValue;

                if (roleId > 0)
                {
                    Role role = ctx.Roles.Single(r => r.Id == roleId);
                    foreach (Permission perm in chkLbox_RolePermissions.CheckedItems)
                    {
                            role.Permissions.Remove(perm);
                    }
                    ctx.SaveChanges();
                    bindingSourcePermissions.DataSource = null;
                    bindingSourcePermissions.DataSource = ctx.Roles.Single(ro => ro.Id == roleId).Permissions.OrderBy(p => p.Id).ToList();
                    ((ListBox)chkLbox_RolePermissions).DataSource = bindingSourcePermissions;
                    ((ListBox)chkLbox_RolePermissions).DisplayMember = "Name";
                    ((ListBox)chkLbox_RolePermissions).ValueMember = "Id";
                }
            }
        }

        private void chkLibox_allPermissions_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (chkLibox_allPermissions.SelectedValue != null)
            {
                int id = ((Permission)chkLibox_allPermissions.SelectedItem).Id;
                if (id > 0)
                {
                    Permission per = ctx.Permissions.Single(p => p.Id == id);
                    lblDescription.Text = per.Description;
                }
            }
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
